package jvm.reference;

import java.lang.ref.SoftReference;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 软引用
 * <P> Date: 2022/3/22:19:46
 * <P> Description:
 */

public class SoftReferenceTest {


    public static class User{
        public Integer id;
        public String name;

        public User(Integer id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) {
        //创建对象 建立软引用
        SoftReference softReference = new SoftReference<User>(new User(2,"1"));
        //这下面等同上面一句话
//        User user = new User(2, "1");
//        SoftReference<User> userSoftReference = new SoftReference<User>(user);
//        user = null;
        System.out.println(softReference.get());

        System.gc();

        System.out.println("After GC");
        //垃圾回收后获得软引用中的对象
        System.out.println(softReference.get());
        try {
            //手动增加内存资源 让系统认为资源不够
          //  byte[] bytes = new byte[1024*1024*7];
            byte[] bytes = new byte[1024*7168-600*1024];
        }catch (Throwable e){
            e.printStackTrace();
        }finally {
            //再次从软引用中获取数据
            //在内存不足时候 垃圾回收器会回收对象
            System.out.println("最后输出"+softReference.get());
        }

    }
}
